import React, {Component} from 'react'
import {Menu, Icon} from 'antd'
import {Link,withRouter} from 'react-router-dom'
import './index.less'
import MenuList from '../../config/menuConfig'
import logo from '../../assets/images/logo.png'

const Item = Menu.Item
const SubMenu = Menu.SubMenu
class LeftNav extends Component {

  getMenuNodes = (list)=>{
    return list.reduce((pre,item)=>{
      if(!item.children){
        pre.push((
          <Item key={item.key}>
            <Link to={item.key}>
              <Icon type={item.icon} />
              <span>{item.title}</span>
            </Link>
          </Item>
        ))
      }else{
        //OpenKey
        const path = this.props.location.pathname
        const cItem = item.children.find(cItem=> path.indexOf(cItem.key)===0)
        if(cItem){
          const openKey = item.key
          this.openKey = openKey
        }

        pre.push((
          <SubMenu key={item.key} title={<span><Icon type={item.icon} /><span>{item.title}</span></span>}>
            {
              this.getMenuNodes(item.children)
            }
          </SubMenu>
        ))
      }
      return pre
    },[])
  }
  componentWillMount(){
    this.menuNodes = this.getMenuNodes(MenuList)
  }

  render () {
    const menuNodes = this.menuNodes
    let selectKey = this.props.location.pathname
    if(selectKey.indexOf(/product/)===0){
      selectKey ='/product'
    }
    const openKey = this.openKey
    return (
      <div className='left-nav'>
        <Link className="logo" to='/home'>
          <img src={logo} alt="logo"/>
          <h1>WebSGG</h1>
        </Link>
        <Menu
          mode="inline"
          theme="dark"
          defaultSelectedKeys={[selectKey]}
          defaultOpenKeys={[openKey]}
        >
          {
            menuNodes
          }
        </Menu>
      </div>
    )
  }
}

export default withRouter(LeftNav)
/*
return MenuList.map(item =>{
  if(!item.children){
    return (
      <Item key={item.key}>
        <Icon type={item.icon}/>
        <span>{item.title}</span>
      </Item>
    )
  }else{
    return(
      <SubMenu key={item.key} title={<span><Icon type={item.icon} /><span>{item.title}</span></span>}>
        {
          item.children.map(childItem =>(
            <Item key={childItem.key}>
              <Icon type={childItem.icon}/>
              <span>{childItem.title}</span>
            </Item>
          ))
        }
      </SubMenu>
    )
  }
})
*/